import {
    getSessionKeyByCode
} from '../api/authorize.js'
export const appAuthorize = {
    onLaunch: function() {
        // 已经获取到token了
        if (this.$storage.getStorage(this.$config.tokenKey)) {
            // 授权了
            this.$u.vuex('vuex_hadAuthorize', true);
        } else {
            // 登录
            this.$uniPromise.login().then((loginRes) => {
                // 判断是否登录成功
                if (loginRes.code) {
                    return getSessionKeyByCode({
                        appid: this.$config.appid,
                        js_code: loginRes.code
                    })
                } else {
                    this.$u.vuex('vuex_hadAuthorize', false);
                }
            }).then((data) => {
                this.$u.vuex('vuex_sessionKey', data.session_key);
                this.$u.vuex('vuex_openid', data.openid);
                // 获取用户的头像和昵称等信息
                return this.$uniPromise.getUserInfo()
            }).then((infoRes) => {
                console.log(infoRes);
                this.setUserInfo(infoRes);
            }).catch((err) => {
                this.$u.vuex('vuex_hadAuthorize', false);
            })
        }
    },
    methods: {
        // 设置用户信息
        setUserInfo(infoRes) {
            this.$u.vuex('vuex_nickName', infoRes.userInfo.nickName);
            this.$u.vuex('vuex_avatarUrl', infoRes.userInfo.avatarUrl);
        },
    }
}
